<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use fast\Random;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Db;
use think\Lang;
use think\Response;
use think\Validate;
use think\Request;
use ZipArchive;

/**
 * 期刊期数
 *
 * @icon fa fa-circle-o
 */
class Qikanqishu extends Backend
{

    /**
     * Qikanqishu模型对象
     * @var \app\admin\model\Qikanqishu
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Qikanqishu;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->param('ids/d') != 0) {
            $this->assignconfig("qikan_id", $this->request->param("ids"));
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                //var_dump($this->request->param());
                $q_word = input('q_word/a');
                $qikan_id = $this->request->param('custom/a');
                $qikan_id = $qikan_id['qikan_id'];
                $total = Db::name('qikanqishu')->where(['qikan_id' => $qikan_id])->count();
                $rs = Db::name('qikanqishu')->field('id,qishu')->where(['qikan_id' => $qikan_id])
                    ->where(function ($query) use ($q_word) {
                        if (isset($q_word[0]) && !empty($q_word[0])) {
                            $query->where('qishu', 'like', '%' . $q_word[0] . '%');
                        }
                    })->order('weigh desc')
                    ->paginate(10, false, ['page' => input('pageNumber', 1)])
                    ->toJson();
                return json(['list' => json_decode($rs, 1), 'total' => $total]);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->request->has("qikan_id")) {
                $list = $this->model
                    ->with(['qikan'])
                    ->where($where)
                    ->where(['qikan_id' => $this->request->param("qikan_id")])
                    ->order($sort, $order)
                    ->paginate($limit);
            } else {
                $list = $this->model
                    ->with(['qikan'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }

            foreach ($list as $row) {

                $row->getRelation('qikan')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 上传文件
     */
    public function upload_zip()
    {
        Config::set('default_return_type', 'json');

        //必须还原upload配置,否则分片及cdnurl函数计算错误
        Config::load(APP_PATH . 'extra/upload.php', 'upload');

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');

            try {
                $upload = new Upload($file);
                $attachment = $upload->upload2();


                $zipFile = $attachment->url;
                $zip = new ZipArchive;

                if ($zip->open('.' . $zipFile) === true) {
                    $zip_url = '/uploads/zip/' . getMillisecond() . '/';
                    $zip->extractTo('.' . $zip_url);
                    $zip->close();
                    //echo '解压成功！';
                } else {
                    //echo '解压失败！';
                }
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true), 'zip_url' => $zip_url]);
        }
    }
}
